package com.sky.elk;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.CollectionUtils;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@SpringBootApplication
public class ElkTrunkApplication {

	public static void main(String[] args) {
		String gelfHost = System.getProperty("gelf");
		if (StrUtil.isBlank(gelfHost)) {
			System.setProperty("gelf", "192.168.31.16");
		}
		String serviceIP = System.getProperty("serviceIP");
		if (StrUtil.isBlank(serviceIP)) {
			try {
				List<String> list = getLocalIPList();
				System.out.println("获取本机总共IP：==== " + JSONObject.toJSONString(list));
				if (!CollectionUtils.isEmpty(list)) {
					System.setProperty("serviceIP", list.get(0));
				} else {
					System.out.println("启动失败，获取本地IP失败");
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		SpringApplication.run(ElkTrunkApplication.class, args);
	}

	public static List<String> getLocalIPList() {
		List<String> ipList = new ArrayList<>();
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			NetworkInterface networkInterface;
			Enumeration<InetAddress> inetAddresses;
			InetAddress inetAddress;
			String ip;
			while (networkInterfaces.hasMoreElements()) {
				networkInterface = networkInterfaces.nextElement();
				inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
						ip = inetAddress.getHostAddress();
						ipList.add(ip);
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ipList;
	}

}
